﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections;
using System.Data;
using System.Text.RegularExpressions;
namespace CrazyTalk.Common
{
    /// <summary>
    ///JSON 的摘要说明
    /// </summary>
    public class JSON
    {
        public JSON()
        {
        }
        public static string DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss";
        public static string DateFormat = "yyyy'-'MM'-'dd";
        /// <summary>
        /// 将对象输出为json格式字符串
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string Encode(object o)
        {
            if (o == null || o.ToString() == "null") return null;
            if (o is string)
            {
                return o.ToString();
            }
            IsoDateTimeConverter dt = new IsoDateTimeConverter();
            dt.DateTimeFormat = DateTimeFormat;
            return JsonConvert.SerializeObject(o, dt);
        }
        public static string EncodeDate(object o)
        {
            if (o == null || o.ToString() == "null") return null;
            if (o is string)
            {
                return o.ToString();
            }
            IsoDateTimeConverter dt = new IsoDateTimeConverter();
            dt.DateTimeFormat = DateFormat;
            return JsonConvert.SerializeObject(o, dt);
        }
        /// <summary>
        /// 将json格式字符串转换为实体对象
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static object Decode(string json)
        {
            if (String.IsNullOrEmpty(json)) return "";
            object o = JsonConvert.DeserializeObject(json);
            if (o is string)
            {
                o = JsonConvert.DeserializeObject(o.ToString());
            }
            object v = toObject(o);
            return v;
        }
        /// <summary>
        /// 获取json格式的返回数据
        /// </summary>
        /// <param name="status">是否请求成功</param>
        /// <param name="message">返回信息</param>
        /// <returns></returns>
        public static string GetJsonMessage(bool status, object message)
        {
            return Encode(new { status, message });
        }
        /// <summary>
        /// 获取json格式的返回数据
        /// </summary>
        /// <param name="status">是否请求成功</param>
        /// <param name="message">返回信息</param>
        /// <param name="type">返回类型</param>
        /// <returns></returns>
        public static string GetJsonMessage(bool status, object message, string type)
        {
            return Encode(new { status, message, type });
        }
        public static DataTable JsonToDataTable(string strJson)
        {
            //取出表名   
            //var rg = new Regex(@"(?<={)[^|]+(?=|\[)", RegexOptions.IgnoreCase);
            //string strName = rg.Match(strJson).Value;
            DataTable tb = null;
            //去除表名   
            //strJson = strJson.Substring(strJson.IndexOf("[") + 1);
            //strJson = strJson.Substring(0, strJson.IndexOf("]"));
            //strJson = strJson.Replace("\"", "");
            //获取数据   
            var rg = new Regex(@"(?<={)[^}]+(?=})");
            MatchCollection mc = rg.Matches(strJson);
            for (int i = 0; i < mc.Count; i++)
            {
                string strRow = mc[i].Value;
                string[] strRows = strRow.Split(',');
                //创建表   
                if (tb == null)
                {
                    tb = new DataTable();
                    //tb.TableName = strName;
                    tb.TableName = "json";
                    foreach (string str in strRows)
                    {
                        var dc = new DataColumn();
                        string[] strCell = str.Split(':');
                        dc.ColumnName = strCell[0].ToString().Replace("\"", "");
                        tb.Columns.Add(dc);
                    }
                    tb.AcceptChanges();
                }
                //增加内容   
                DataRow dr = tb.NewRow();
                for (int r = 0; r < strRows.Length; r++)
                {
                    //dr[r] = strRows[r].Split('|')[1].Trim().Replace("，", ",").Replace("| ", "|").Replace("\"", "");
                    string ls_data;
                    ls_data = strRows[r];
                    ls_data = strRows[r].Split(':')[1].Trim();
                    ls_data = ls_data.Replace("，", ",");
                    ls_data = ls_data.Replace("：", ":");
                    ls_data = ls_data.Replace("//", "");
                    ls_data = ls_data.Replace("\"", "");
                    dr[r] = ls_data;
                }
                tb.Rows.Add(dr);
                tb.AcceptChanges();
            }
            return tb;
        }
        public static object Decode(string json, Type type)
        {
            return JsonConvert.DeserializeObject(json, type);
        }
        private static object toObject(object o)
        {
            if (o == null) return null;
            if (o is string)
            {
                //判断是否符合2010-09-02T10:00:00的格式
                string s = o.ToString();
                if (s.Length == 19 && s[10] == ' ' && s[4] == '-' && s[13] == ':')
                {
                    o = System.Convert.ToDateTime(o);
                }
            }
            else if (o is JObject)
            {
                JObject jo = o as JObject;
                Hashtable h = new Hashtable();
                foreach (KeyValuePair<string, JToken> entry in jo)
                {
                    h[entry.Key] = toObject(entry.Value);
                }
                o = h;
            }
            else if (o is IList)
            {
                ArrayList list = new ArrayList();
                list.AddRange((o as IList));
                int i = 0, l = list.Count;
                for (; i < l; i++)
                {
                    list[i] = toObject(list[i]);
                }
                o = list;
            }
            else if (typeof(JValue) == o.GetType())
            {
                JValue v = (JValue)o;
                o = toObject(v.Value);
            }
            else
            {
            }
            return o;
        }
        /// <summary>
        /// 返回页面treegrid、tree控件所需要的json数据集
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="pidval">顶级节点的ParentId的值</param>
        /// <param name="pidname">父节点存储Id字段名</param>
        /// <param name="idname">当前节点的Id字段名</param>
        /// <param name="txtname">组织名称的存储字段名</param>
        /// <returns></returns>
        private static string GetDataString(DataTable dt, string Topidval, string pidname, string idname, string txtname)
        {
            StringBuilder stringbuilder = new StringBuilder();
            DataRow[] CRow = dt.Select(pidname + "=" + Topidval);
            if (CRow.Length > 0)
            {
                stringbuilder.Append("[");
                for (int i = 0; i < CRow.Length; i++)
                {
                    string chidstring = GetDataString(dt, CRow[i][idname].ToString(), pidname, idname, txtname);
                    if (!string.IsNullOrEmpty(chidstring))
                    {
                        stringbuilder.Append("{ \"id\":\"" + CRow[i][idname].ToString() + "\",\"text\":\"" + CRow[i][txtname].ToString() + "\",\"state\":\"open\",\"children\":");
                        stringbuilder.Append(chidstring);
                    }
                    else
                    {
                        stringbuilder.Append("{\"id\":\"" + CRow[i][idname].ToString() + "\",\"text\":\"" + CRow[i][txtname].ToString() + "\"},");
                    }
                }
                stringbuilder.Replace(',', ' ', stringbuilder.Length - 1, 1);
                stringbuilder.Append("]},");
            }
            return stringbuilder.ToString();
        }
        /// <summary>
        /// 返回页面treegrid、tree控件所需要的json数据集
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="pidval">顶级节点的ParentId的值</param>
        /// <param name="pidname">父节点存储Id字段名</param>
        /// <param name="idname">当前节点的Id字段名</param>
        /// <param name="txtname">组织名称的存储字段名</param>
        /// <returns></returns>
        public static string GetTreeString(DataTable dt, string Topidval, string pidname, string idname, string txtname)
        {
            string jsontree = GetDataString(dt, Topidval, pidname, idname, txtname);
            jsontree = jsontree.Remove(jsontree.Length - 2, 2);
            return jsontree;
        }
        /// <summary>
        /// 返回页面treegrid、tree控件所需要的json数据集
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="pidval">顶级节点的ParentId的值</param>
        /// <param name="pidname">父节点存储Id字段名</param>
        /// <param name="idname">当前节点的Id字段名</param>
        /// <param name="FieldNames">要输出的字段名</param>
        /// <returns></returns>
        private static string GetDataString(DataTable dt, string Topidval, string pidname, string idname, string[] FieldNames)
        {
            StringBuilder stringbuilder = new StringBuilder();
            DataRow[] CRow = dt.Select(pidname + "=" + Topidval);
            if (CRow.Length > 0)
            {
                stringbuilder.Append("[");
                for (int i = 0; i < CRow.Length; i++)
                {
                    StringBuilder stringbuilder2 = new StringBuilder();
                    stringbuilder2.Append("{ \"id\":\"" + CRow[i][idname].ToString() + "\"");
                    for (int j = 0; j < FieldNames.Length; j++)
                    {
                        string name = FieldNames[j].ToString();
                        stringbuilder2.Append(",\"" + name + "\":\"" + CRow[i][name].ToString() + "\"");
                    }
                    stringbuilder.Append(stringbuilder2.ToString());
                    string chidstring = GetDataString(dt, CRow[i][idname].ToString(), pidname, idname, FieldNames);
                    if (!string.IsNullOrEmpty(chidstring))
                    {
                        stringbuilder.Append(",\"state\":\"open\",\"children\":");
                        stringbuilder.Append(chidstring);
                    }
                    else
                    {
                        stringbuilder.Append("},");
                    }
                }
                stringbuilder.Replace(',', ' ', stringbuilder.Length - 1, 1);
                stringbuilder.Append("]},");
            }
            return stringbuilder.ToString();
        }
        /// <summary>
        /// 返回页面treegrid、tree控件所需要的json数据集
        /// </summary>
        /// <param name="dt">数据源</param>
        /// <param name="pidval">顶级节点的ParentId的值</param>
        /// <param name="pidname">父节点存储Id字段名</param>
        /// <param name="idname">当前节点的Id字段名</param>
        /// <param name="FieldNames">要输出的字段名</param>
        /// <returns></returns>
        public static string GetTreeString(DataTable dt, string Topidval, string pidname, string idname, string[] FieldNames)
        {
            string jsontree = GetDataString(dt, Topidval, pidname, idname, FieldNames);
            jsontree = jsontree.Remove(jsontree.Length - 2, 2);
            return jsontree;
        }
    }
}
